#include "AbstractRoom.h"
#include "../manager/UDPManager.h"

AbstractRoom::AbstractRoom(const quint16& id, QObject* parent)
    : QObject(parent), m_id(id) {}

void AbstractRoom::addClient(AbstractUser* user) {
    if (!m_clients.contains(user)) {
        m_clients.append(user);
        user->joinRoom(this);
    }
}

void AbstractRoom::removeClient(const quint16& userId) {
    for (int i = 0; i < m_clients.size(); ++i) {
        if (m_clients[i]->getID() == userId) {
            m_clients.remove(i);
            return;
        }
    }
}

QVector<quint16> AbstractRoom::getClientIDs() const {
    QVector<quint16> ids;
    ids.reserve(m_clients.size());
    for (const auto& client : m_clients) {
        ids.append(client->getID());
    }
    return ids;
}

void AbstractRoom::broadcast(const QByteArray& msg, quint16 excludeUserId) {
    for (const auto& client : m_clients) {
        if (client->getID() == excludeUserId) continue;
        UDPManager::instance()->sendToUser(client, msg);
    }
}
